package com.duleme.common;

import com.google.gson.*;


import javax.servlet.ServletInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class JsonUtils {

    public static String object2Json(Object o){
        Gson gson=new Gson();
        String json=gson.toJson(o);
        return json;
    }

    public static String getJsonStr(ServletInputStream inputStream){
        BufferedReader reader = null;
        StringBuilder builder = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            String line = null;
            while ((line=reader.readLine())!=null){
                builder.append(line);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return builder.toString();

    }

    public static String toJson(Object obj){
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        String json=gson.toJson(obj);
        return json;
    }
    public static String result2Json(String result){
        Map<String,String> kv=new HashMap<>();
        kv.put("result",result);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        return gson.toJson(kv);
    }

    public static String result2Json(String result,String key,String value){
        Map<String,String> kv=new HashMap<>();
        kv.put("result",result);
        kv.put(key,value);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        return gson.toJson(kv);
    }
//    public static void main(String[] args){
//        List<UserInfo> userInfos=new ArrayList<>();
//        UserInfo user1=new UserInfo();
//        user1.setId("34252219970135222x");
//        user1.setBirthday(new Date());
//        user1.setEmailAddress("222@qq.com");
//        user1.setName("wxy");
//        user1.setPhoneNumber("13343331212");
//        user1.setSex(0);
//        user1.setUserId(1);
//        UserInfo user2=new UserInfo();
//        user2.setId("34252219970135222x");
//        user2.setBirthday(new Date());
//        user2.setEmailAddress("222@qq.com");
//        user2.setName("SGN");
//        user2.setPhoneNumber("13343331212");
//        user2.setSex(1);
//        user2.setUserId(2);
//        userInfos.add(user1);
//        userInfos.add(user2);
//        System.out.println(new JsonUtils().userInfos2Json(userInfos));
//    }
}
